let myfn = {};


/**
 * 预览图片
 * vk.myfn.previewImage()
 * @param {Array} e 图片数组
 * @param {Number} current 当前显示图片的索引
 * @returns {void}
 */
myfn.previewImage = (e, current) => {
	let urls = e.map(item => item.url);
	uni.previewImage({
		urls,
		current: current ? current : 0,
	});
}


/**
 * 格式化时间
 * vk.myfn.formatTime()
 * @param {String} date 时间戳
 * @returns {String}
 */
myfn.formatTime = (date) => {
	const formatter = new Date(date.replace(/-/g, '/'));

	const now = new Date();
	const diff = Math.abs(now - formatter) / 1000; // 时间差，单位为秒
	const intervals = {
		年: 31536000,
		个月: 2592000,
		天: 86400,
		小时: 3600,
		分钟: 60,
		秒: 1
	};
	for (let unit in intervals) {
		const value = Math.floor(diff / intervals[unit]);
		if (value > 0) {
			return value === 1 ? `1 ${unit}前` : `${value} ${unit}前`;
		}
	}
	return '刚刚';
}


/**
 * 对象转字符串
 * vk.myfn.objToString()
 * @param {Object} obj 对象
 * @returns {String}
 */
myfn.objToString = (obj) => {
	let str = '?';
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			str += `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}&`;
		}
	}
	return str.slice(0, -1);
}

export default myfn;